﻿using System;
using System.Reflection;
using NAnt.Core;
using NAnt.Core.Attributes;
using RikMigrations.Providers;

namespace RikMigrations.Nant
{
    [TaskName("migrate")]
    public class MigrateTask : Task
    {
        private int? version;
        private string module;
        private string assembly;
        private string catalog;
        private string server;
        private string username;
        private string password;

        [TaskAttribute("version", Required = false)]
        public int? Version
        {
            get { return version; }
            set { version = value; }
        }

        [TaskAttribute("module", Required = false)]
        public string Module
        {
            get { return module; }
            set { module = value; }
        }

        [TaskAttribute("assembly", Required = true)]
        public string AssemblyName
        {
            get { return assembly; }
            set { assembly = value; }
        }

        [TaskAttribute("catalog", Required = true)]
        public string Catalog
        {
            get { return catalog; }
            set { catalog = value; }
        }

        [TaskAttribute("server", Required = true)]
        public string Server
        {
            get { return server; }
            set { server = value; }
        }

        [TaskAttribute("username", Required = false)]
        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        [TaskAttribute("password", Required = false)]
        public string Password
        {
            get { return password; }
            set { password = value; }
        }


        protected override void ExecuteTask()
        {
            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
            {
                DbProvider.DefaultConnectionString =
                    string.Format("data source={0};initial catalog={1};user id={2};password={3}", Server,
                                  catalog, username, password);
            }
            else
            {
                DbProvider.DefaultConnectionString =
                            string.Format("data source={0};initial catalog={1};Integrated Security=SSPI;", server,
                                          catalog);
            }

            if (version == null)
            {
                MigrationManager.UpgradeMax(System.Reflection.Assembly.LoadFrom(AssemblyName),
                                                    new MssqlProvider(), new string[] { module });
            } else
            {
                MigrationManager.MigrateTo(System.Reflection.Assembly.LoadFrom(AssemblyName),
                                                   module,
                                                   Version.Value);
            }


        }
    }
}
